//
//  SearchListViewController.m
//  customer
//
//  Created by 往返网络 on 17/8/24.
//  Copyright © 2017年 com. All rights reserved.
//

#import "SearchListViewController.h" //搜索列表页
#import "SearchViewController.h" //搜索页面id号
#import "FahuoTableViewCell.h" //发货cell
#import "FahuoDetailViewController.h" //发货运单详情界面，没有操作（收藏后期加入）／中转／外包详情也用此界面，公司名称的值有所不同
#import "PublicMethod.h"

//定义搜索URL
#define URL_SEARCH [NSString stringWithFormat:@"%@/Appcustomernewer/Order/searchOrder?type=get",BASE_URL]

@interface SearchListViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UIView * searchview;
@property (nonatomic,strong)UITextField * searchbartf1;
@property (nonatomic,strong)NSMutableArray * resultArray; //结果数据源
@property (nonatomic,strong)NSMutableArray * dataSource;  //总数据源
@property (nonatomic,strong)AFHTTPSessionManager* manger;
@property (nonatomic,strong)NSMutableDictionary * docu_data; //运单数据

@end

@implementation SearchListViewController
{
    UITableView * tableview;

}
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    [self loadDatawithString:self.doucu_string];
    [self createUI];
    // Do any additional setup after loading the view.
}


- (void)loadDatawithString:(NSString *)searchstring{
    //请求数据源
    [self.resultArray removeAllObjects];
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
    //去除空格和换行
    searchstring = [searchstring stringByReplacingOccurrencesOfString: @" " withString: @""];
    searchstring = [searchstring stringByReplacingOccurrencesOfString: @"\n" withString: @""];

    NSString * url = [NSString stringWithFormat:@"%@&token=%@&ordersn=%@",URL_SEARCH,token,searchstring];
    NSString * URL = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"search url %@",url);
    //播放动画
    UIImageView * im = [PublicMethod startAnimation];
    
    [self.manger GET:URL parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSInteger code = [dict[@"code"]integerValue];
            
            if (code == 0) {
                // 停止动画
                [im stopAnimating];
                //运单详情数据
                _docu_data = [NSMutableDictionary dictionaryWithDictionary:dict[@"data"]];
                NSLog(@"data %@",_docu_data);
                //result 存放结果
                self.resultArray  = [NSMutableArray arrayWithObject:_docu_data];
                [tableview reloadData];
                
            }else{
                
                [im stopAnimating];
                [tableview reloadData];
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
            }
            
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
        [im stopAnimating];
        
    }];

}




- (void)createUI{
    
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    float fontsize = 17;
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        
        fontsize = 17;
    }
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    //设置表头
    UIView * titleview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    titleview.backgroundColor = COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:titleview];
    _searchview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    _searchview.backgroundColor = COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:_searchview];
    
    float cornersizeSearch = 15; //searchbar的圆角大小
    
    UIFont * iconfont = [UIFont fontWithName:@"iconfont" size:fontsize];
    
    cornersizeSearch = SCREEN_H < 667 ? 13 : 16 ;
    
    fontsize = SCREEN_H < 667 ? 12 : 16 ;
    
    if (SCREEN_H == 667) {
        
        iconfont = [UIFont fontWithName:@"iconfont" size:18];
        
        fontsize = 14;
        
        cornersizeSearch = 15;
    }
    UIButton * leftlable  = [[UIButton alloc]initWithFrame:CGRectMake(0, 20+14.0/1334*SCREEN_H, 80.0/W_BASE*SCREEN_W, 60.0/1334.0*SCREEN_H)];
    
    [leftlable setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    leftlable.titleLabel.font = [UIFont fontWithName:@"iconfont" size:fontsize+8];
    
    [leftlable setTitle:@"\U0000e697" forState:UIControlStateNormal];
    
    [leftlable.titleLabel setTextAlignment:NSTextAlignmentCenter];
    
    [leftlable addTarget:self action:@selector(returnLast) forControlEvents:UIControlEventTouchUpInside];
    
    [_searchview addSubview:leftlable];

    _searchbartf1 = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(leftlable.frame), 20+14.0/1334*SCREEN_H, 640.0/W_BASE*SCREEN_W, 60.0/1334*SCREEN_H)];
    
    _searchbartf1.backgroundColor = [UIColor whiteColor];
    
    _searchbartf1.placeholder = @"搜索运单编号";
    
    _searchbartf1.layer.cornerRadius = cornersizeSearch;
    
    _searchbartf1.layer.borderColor = [[UIColor whiteColor]CGColor];
    
    _searchbartf1.layer.borderWidth = 1;
    
    _searchbartf1.delegate = self;
    _searchbartf1.keyboardType = UIKeyboardTypeASCIICapable;
    
    _searchbartf1.clipsToBounds = YES;
    
    //设置tf中placeholder的字体颜色
    
    [_searchbartf1 setValue:COLORRGBA(153, 153, 153, 1)  forKeyPath:@"_placeholderLabel.textColor"];
    
    _searchbartf1.font = [UIFont systemFontOfSize:fontsize];
    
    [_searchview addSubview:_searchbartf1];
    _searchbartf1.text = self.doucu_string;
    _searchbartf1.clearButtonMode = UITextFieldViewModeWhileEditing;
    _searchbartf1.returnKeyType=UIReturnKeySearch;

    UIButton * leftbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80.0/750*SCREEN_W , 70.0/1334*SCREEN_H)];
    
    leftbtn.titleLabel.font = [UIFont fontWithName:@"iconfont" size:fontsize+2];
    
    [leftbtn setTitle:@"\U0000e6ac" forState:UIControlStateNormal];
    
    [leftbtn setTitleColor:COLORRGBA(153, 153, 153, 1) forState:UIControlStateNormal];
    
    _searchbartf1.leftView = leftbtn;
    
    _searchbartf1.leftViewMode = UITextFieldViewModeAlways;
    
    tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_W, SCREEN_H-64) style:UITableViewStylePlain];
    tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    tableview.rowHeight = 44;
    
    tableview.delegate = self;
    
    tableview.dataSource = self;
    
    tableview.backgroundColor = COLORRGBA(239, 239, 239, 1);
    [tableview registerClass:[FahuoTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:tableview];
}

#pragma mark -- Tableview-Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 365.0/H_BASE*SCREEN_H;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.resultArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FahuoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
//    cell.isfahuo = @"YES";
    SendListModel * model = [[SendListModel alloc]init];
    NSDictionary * dict  = (NSDictionary*)[self.resultArray objectAtIndex:indexPath.row];
   //判定显示哪个goods_name(1有名称则优先显示)
    NSString * goods_name1  = [NSString stringWithFormat:@"%@",dict[@"goods_name1"]];
    NSString * goods_name2  = [NSString stringWithFormat:@"%@",dict[@"goods_name2"]];
    NSString * goods_name3  = [NSString stringWithFormat:@"%@",dict[@"goods_name3"]];
    if (goods_name1.length != 0) {
        model.goods_name = goods_name1;
        model.goods_num  = [NSString stringWithFormat:@"%@",dict[@"goods_num1"]];
        model.goods_volume = [NSString stringWithFormat:@"%@",dict[@"goods_volume1"]];
        model.goods_weight = [NSString stringWithFormat:@"%@",dict[@"goods_weight1"]];
    }else if (goods_name2.length != 0){
        model.goods_name = goods_name2;
        model.goods_num  = [NSString stringWithFormat:@"%@",dict[@"goods_num2"]];
        model.goods_volume = [NSString stringWithFormat:@"%@",dict[@"goods_volume2"]];
        model.goods_weight = [NSString stringWithFormat:@"%@",dict[@"goods_weight2"]];
    }else if (goods_name3.length != 0){
        model.goods_name = goods_name3;
        model.goods_num  = [NSString stringWithFormat:@"%@",dict[@"goods_num3"]];
        model.goods_volume = [NSString stringWithFormat:@"%@",dict[@"goods_volume3"]];
        model.goods_weight = [NSString stringWithFormat:@"%@",dict[@"goods_weight3"]];
    }else{ //都为空时
        model.goods_name = goods_name1;
        model.goods_num  = [NSString stringWithFormat:@"%@",dict[@"goods_num1"]];
        model.goods_volume = [NSString stringWithFormat:@"%@",dict[@"goods_volume1"]];
        model.goods_weight = [NSString stringWithFormat:@"%@",dict[@"goods_weight1"]];
    }
    NSLog(@"goods_name1 %@,name2 %@,name3 %@",goods_name1,goods_name2,goods_name3);
    
    model.id  = [NSString stringWithFormat:@"%@",dict[@"id"]];
    model.order_id  = [NSString stringWithFormat:@"%@",dict[@"order_id"]];
    model.to_person  = [NSString stringWithFormat:@"%@",dict[@"from_person"]];
    model.to_mobile  = [NSString stringWithFormat:@"%@",dict[@"from_mobile"]];
    model.company_name  = [NSString stringWithFormat:@"%@",dict[@"company_name"]];
    model.created_time  = [NSString stringWithFormat:@"%@",dict[@"created_time"]];
    model.order_state  = [NSString stringWithFormat:@"%@",dict[@"order_state"]];
    model.created_time  = [NSString stringWithFormat:@"%@",dict[@"created_time"]];
    model.fee  = [NSString stringWithFormat:@"%@",dict[@"fee"]];
    [cell refreshCellWithModel:model];
    
    cell.block1 = ^(NSString * isPhone){
        
        //拨打电话
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",isPhone];
        
        UIWebView * callWebview = [[UIWebView alloc] init];
        
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
        
        [self.view addSubview:callWebview];
        
    };
    
    cell.block2 = ^(NSString * followid){
        
        //运单详情界面
        FahuoDetailViewController * detail = [[FahuoDetailViewController alloc]init];
        
        detail.isDetail = @"NO";
        
        NSString * oid = model.id;
        
        detail.oid = oid;
        
        [self presentViewController:detail animated:YES completion:nil];
    };
    
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //进入详情界面
    
    SendListModel * model = [[SendListModel alloc]init];
    NSDictionary * dict = (NSDictionary *)self.resultArray[indexPath.row];
    model.id  = dict[@"id"];

    FahuoDetailViewController * detail = [[FahuoDetailViewController alloc]init];
    
    detail.isDetail = @"YES";
    
    detail.oid = model.id;
    
    [self presentViewController:detail animated:YES completion:nil];

    [tableView deselectRowAtIndexPath:indexPath animated:NO]; //效果完成，之后点击cell抬起手指之后，就没有那个选中的灰色背景颜色了。
    
}


//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    
//    //不断输入，不断查询请求数据源
//    [self.resultArray removeAllObjects];
//    //加个多线程，否则数量量大的时候，有明显的卡顿现象
//    //这里最好放在数据库里面再进行搜索，效率会更快一些
//    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
//    dispatch_async(globalQueue, ^{
//        
//        if (_searchbartf1.text!=nil && _searchbartf1.text.length>0) {
//            
//            //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
//            
//            for (int i = 0; i< self.dataSource.count; i++) {
//                
//                NSString *tempStr = self.dataSource[i];
//                
//                NSString *pinyin = [self transformToPinyin:tempStr];
//                
//                if ([pinyin rangeOfString:_searchbartf1.text options:NSCaseInsensitiveSearch].length >0 ) {
//                    
//                    [self.resultArray addObject:tempStr];
//                }
//                
//            }
//        }
//        
//        //回到主线程
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            [tableview reloadData];
//            
//        });
//        
//    });
//    
//    return YES;
//    
//}

- (NSString *)transformToPinyin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    int count = 0;
    
    for (int  i = 0; i < pinyinArray.count; i++)
    {
        
        for(int i = 0; i < pinyinArray.count;i++)
        {
            if (i == count) {
                [allString appendString:@"#"];//区分第几个字母
            }
            [allString appendFormat:@"%@",pinyinArray[i]];
            
        }
        [allString appendString:@","];
        count ++;
        
    }
    
    NSMutableString *initialStr = [NSMutableString new];//拼音首字母
    
    for (NSString *s in pinyinArray)
    {
        if (s.length > 0)
        {
            
            [initialStr appendString:  [s substringToIndex:1]];
        }
    }
    
    [allString appendFormat:@"#%@",initialStr];
    [allString appendFormat:@",#%@",aString];
    
    return allString;
}

- (void)returnLast{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.view endEditing:YES];
    [self loadDatawithString:_searchbartf1.text];//请求数据
    return YES;
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
}

- (NSMutableArray *)resultArray{
    
    if (!_resultArray) {
        _resultArray  = [NSMutableArray array];
    }
    return _resultArray;
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark - - -- - - - 懒加载 ---- - -- - -

- (AFHTTPSessionManager*)manger{
    
    if (!_manger) {
        
        _manger = [AFHTTPSessionManager manager];
        
        _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
        
    }
    
    return _manger;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
